//------------------------------------------------------------------------------
//  <copyright file="StaticMapLocalizationAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Navigation.Runtime.Localization
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Hardware.DAC;
    using Microsoft.Robotics.Hardware.Runtime.DAC;
    using Microsoft.Robotics.Navigation.Localization;
    using Microsoft.Robotics.Navigation.Motion;
    using Microsoft.Robotics.Navigation.Perception;
    using Microsoft.Robotics.Navigation.Runtime.Localization;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Tracing;

    /// <summary>
    /// Agent that determining the robot location on a static map.
    /// </summary>
    /// <typeparam name="TDriveFeedbackState">The drive feedback state type used for motion update</typeparam>
    [DataContract]
    public class StaticMapLocalizationAgent<TDriveFeedbackState> : ParticleFilterLocalizationAgent<LocalizationParticleFilter<TDriveFeedbackState>, SLAM2DParticle, KinectHorizontalDepthProfile, SLAM2DAgentMessage, TDriveFeedbackState>, IControlReceiver<SimpleAgentMessage<Pose2D>> 
        where TDriveFeedbackState : IDriveState
    {
        /// <summary>
        /// The global map
        /// </summary>
        private GlobalMap globalMap;

        /// <summary>
        /// The resolution of the global map
        /// </summary>
        private float distanceResolution;

        /// <summary>
        /// Initializes a new instance of the StaticMapLocalizationAgent class
        /// </summary>
        /// <param name="name">Agent name</param>
        /// <param name="localMapProducer">The name of the local map to subscribe to</param>
        /// <param name="driveFeedbackProducer">Drive feedback producer to subscribe to</param>
        /// <param name="robotConfigFolder">The robot config folder.</param>
        /// <param name="distanceResolution">The actual distance resolution.</param>
        /// <param name="particleCount">The number of particles for the particle filter.</param>
        /// <param name="mapFile">The map to load.</param>
        /// <param name="robotStartPose">The start pose of the robot.</param>
        /// <param name="robotStartPoseVariance">The ambiguity in the start pose.</param>
        public StaticMapLocalizationAgent(
            string name,
            IProducer<SimpleAgentMessage<KinectHorizontalDepthProfile>> localMapProducer,
            IProducer<SimpleAgentMessage<TDriveFeedbackState>> driveFeedbackProducer,
            string robotConfigFolder,
            float distanceResolution,
            int particleCount,
            string mapFile,
            Pose2D robotStartPose,
            Pose2D robotStartPoseVariance)
            : base(name, localMapProducer, driveFeedbackProducer, robotConfigFolder, distanceResolution, particleCount, mapFile, robotStartPose, robotStartPoseVariance)
        {
        }

        /// <summary>
        /// Message to Reset the particle filter to a new pose
        /// </summary>
        /// <param name="message">A simple message with a Pose2D</param>
        public void ReceiveControl(SimpleAgentMessage<Pose2D> message)
        {
            this.ResetFilter(this.globalMap, this.distanceResolution, message.State);
        }

        /// <summary>
        /// Creates a new LocalizationParticleFilter from a map and a resolution
        /// </summary>
        /// <param name="map">The map to start with.</param>
        /// <param name="distanceResolution">The resolution of the map</param>
        /// <param name="robotStartPose">The starting pose.</param>
        /// <returns>The message to publish</returns>
        protected override LocalizationParticleFilter<TDriveFeedbackState> CreateFilter(GlobalMap map, float distanceResolution, Pose2D robotStartPose)
        {
            this.globalMap = map;
            this.distanceResolution = distanceResolution;
            this.RobotStartPose = robotStartPose;

            return new LocalizationParticleFilter<TDriveFeedbackState>(map, this.ParticleCount, this.RobotStartPose, this.RobotStartPoseVariance);
        }

        /// <summary>
        /// Creates a new message to publish, based on the agent state. Called every time the filter is updated.
        /// </summary>
        /// <param name="initiatingMessage">
        /// The lower-level message that triggered the creation of this message.
        /// </param>
        /// <returns>The message to publish</returns>
        protected override SLAM2DAgentMessage CreateMessage(SimpleAgentMessage<KinectHorizontalDepthProfile> initiatingMessage)
        {
            Pose2D mapStartPose = this.Filter.Particles[0].Map.MapStartPose;

            // TODO: merge with identical method in SLAM2DAgent
            Pose2D[] poses = new Pose2D[this.ParticleCount];
            for (int i = 0; i < this.ParticleCount; i++)
            {
                poses[i] = this.GetPoseInGlobalCoordinates(this.Filter.Particles[i].Pose, mapStartPose);
            }

            SLAM2DParticle likelyParticle = this.Filter.GetHighestLikelihoodParticle();
            SLAM2DParticle[] particles = (SLAM2DParticle[])this.Filter.Particles.Clone();
            Pose2D likelyPose = likelyParticle.Pose;
            ////IEnumerable<SLAM2DParticle> bestParticles = particles.OrderBy(p => p.Weight).Take(10);
            ////double totalWeight = bestParticles.Sum(p => p.Weight);
            ////if (totalWeight != 0)
            ////{
            ////    likelyPose = bestParticles.Aggregate(new Pose2D(), (accumulator, particle) => accumulator + particle.Pose * particle.Weight);
            ////    likelyPose = likelyPose * (1 / totalWeight);

            ////    // the average of a heading as done above doesn't make any sense, so replace it with the heading of the most likely particle
            ////    likelyPose.Heading = likelyParticle.Pose.Heading;
            ////}

            likelyPose = this.GetPoseInGlobalCoordinates(likelyPose, mapStartPose);

            SLAM2DAgentMessage newMessage = new SLAM2DAgentMessage(likelyParticle.Map, likelyPose, poses, particles, initiatingMessage);
            return newMessage;
        }
    }
}
